package com.zaofan.service;

import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;

import com.zaofan.bean.Topic;
import com.zaofan.bean.TopicReply;
import com.zaofan.bean.TopicReplyDTO;
import com.zaofan.dao.TopicDao;
import com.zaofan.dao.TopicReplyDao;
import com.zaofan.exception.ServiceException;
import com.zaofan.utils.C3p0DataSourceUtils;
import com.zaofan.utils.SqlBuilderUtils;

public class TopicReplyService {

	private TopicReplyDao topicReplyDao = new TopicReplyDao();

	private TopicDao topicService = new TopicDao();

	public void add(TopicReply topicReply) {
		topicReplyDao.add(topicReply);
	}

	public void del(TopicReply topicReply) {
		topicReplyDao.del(topicReply);
	}

	public Long count(Map<String, Object> params) {
		return topicReplyDao.count(params);
	}

	public TopicReply findById(Integer id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		return topicReplyDao.findOne(params);
	}

	public List<TopicReplyDTO> findByTopicIdWithOther(String begin, String end, String topicId, String replyType,
			String type) {
		List<TopicReplyDTO> replys = topicReplyDao.findByTopicIdWithOther(begin, end, topicId, replyType, type);
		return replys;
	}

	public Long countByTopicIdWithOther(String topicId, String replyType, String type) {
		return topicReplyDao.countByTopicIdWithOther(topicId, replyType, type);
	}

	public void update(TopicReply topicReply) {
		topicReplyDao.update(topicReply);

	}

	public void delReply(TopicReply topicReply) throws Exception {
		Topic topic = topicService.findById(topicReply.getReplyId());
		if (topic == null) {
			throw new ServiceException("参数错误");
		}
		try {
			Connection connection = C3p0DataSourceUtils.getConnection();
			QueryRunner runner = new QueryRunner();
			String sql = "";
			try {
				connection.setAutoCommit(false);
				if (topicReply.getReplyType() == 0) {
					topic.setPraise(topic.getPraise() - 1);
				} else {
					topic.setCount(topic.getCount() - 1);
				}
				// 更新 话题的 相关数量
				sql = SqlBuilderUtils.builderUpdateSql(Topic.class, topic);
				System.err.println(sql);
				runner.update(connection, sql);
				sql = SqlBuilderUtils.builderDelSql(TopicReply.class, topicReply);
				System.err.println(sql);
				runner.update(connection, sql);
				connection.commit();
			} catch (Exception e) {
				connection.rollback();
				e.printStackTrace();
				throw e;
			} finally {
				connection.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

	}

	public TopicReply findPraiseReplyByUserIdAndReplyId(Integer userId, Integer id) {
		Map<String, Object> params = new HashMap<>();
		params.put("userId", userId + "");
		params.put("replyId", id + "");
		params.put("replyType", 0 + "");
		return this.topicReplyDao.findOne(params);
	}

}
